const appConfig = require('/config/config.js');
const tip = require('/utils/tip.js');
const http = require('/utils/http.js');
//app.js
App({
  onLaunch: function() {
    // 展示本地存储能力
    let that = this;
    var logs = wx.getStorageSync('logs') || []
    var userId = wx.getStorageSync('userId') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    wx.setStorageSync('userId', userId)
    wx.getSystemInfo({
      success: function (res) {
        that.globalData.systemInfo = res;
      },
    })
    wx.checkSession({
      success() {
        // session_key 未过期，并且在本生命周期一直有效
        
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        // 登录
        wx.login({
          success: res => {
            console.log(res)
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            if (res.code) {
              var code = res.code;
              wx.getUserInfo({
                success: res => {
                  console.log(res);

                  //发起网络请求
                  wx.request({
                    url: appConfig.baseUrl + 'Login/DoLogin',
                    data: {
                      code: code,
                      encryptedData: res.encryptedData,
                      iv: res.iv,
                      rawData: res.rawData,
                      signature: res.signature
                    },
                    method: 'POST',
                    success: function(res) {
                      console.log(res);
                    },
                    fail: function(res) {
                      console.log(res);
                    }
                  });
                }
              })

            } else {
              console.log('获取用户登录态失败！' + res.errMsg)
            }
          }
        })
      }
    });


    // 获取用户信息
    wx.getSetting({
      success: res => {
        
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              console.log(res);
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        } else {
          wx.reLaunch({
            url: '/pages/authorize/authorize',
          })
        }
        //相册授权
        if (res.authSetting["scope.writePhotosAlbum"] == false)
        {
          wx.showModal({
            title: '授权提醒',
            content: '需要您授权保存相册',
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {
                  console.log("settingdata", settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限成功',
                      showCancel: false,
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限失败，将无法保存到相册哦~',
                      showCancel: false,
                    })
                  }
                },
                fail(failData) {
                  console.log("failData", failData)
                },
                complete(finishData) {
                  console.log("finishData", finishData)
                }
              })
            }
          });
        }
      }
    })
  },
  /**
   *@param {function} cb 处理地理位置
   */
  getLocationInfo: function (cb) {
    var that = this;
    if (this.globalData.locationInfo) {
      cb(this.globalData.locationInfo)
    } else {
      wx.getLocation({
        type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
        success: function (res) {
          that.globalData.locationInfo = res;
          cb(that.globalData.locationInfo)
        },
        fail: function (res) {
          console.log(res);
        }
      })
    }
  },
  /**
   * 订阅系统推送消息
   * @param {*} e 
   */
  subscribeAdapter:function(userId,noticeId,cb){
    tip.showModal("授权订阅","是否订阅寻宠寻主推送消息？",function(data){
      if (data.confirm) {
        
        wx.requestSubscribeMessage({
          tmplIds: [appConfig.msgTemplate],
          success(res) {
            console.log(res);
            //var acceptTemplateIds = Object.keys(res).filter(key => res[key] === 'accept');
            console.log(res[appConfig.msgTemplate]);
            if (res[appConfig.msgTemplate] == "accept") {
              //推送消息
              http.post(appConfig.baseUrl + 'Notice/SubscribeNotice', {
                ReplyUserId: userId,
                NoticeId:noticeId
              }, function (res) {
                console.log(res.data)
                if (res.data.Flag == true) {
                  tip.showModal('订阅成功','寻TA将为您及时推送订阅信息');
                  cb();
                }
              }, function (res) {
                tip.showToast('系统繁忙，请稍后再试！');
                cb();
              });
            }
          },fail(ret){
            console.log(ret);
            tip.showToast('抱歉，订阅失败，请稍后再试');
            cb();
          }
        });
       } else if (data.cancel) {
        cb();
       }
    
    });
    

  },
  globalData: {
    userInfo: null,
    locationInfo:null,
    systemInfo: null
  }
})